import { defineStore } from "pinia";
import {
  getUUID,
  getGUID,
  downloadTextFile,
  JSONStringify,
  canvasCut,
} from "@/utils/index";
import i18n from "@/locales/index.js";
import { getMaterial } from "@/api/specs";
import { getlabelsList } from "@/api/labels";
import getEnvConfig from "@/config/axios/getEnvConfig";

const { t } = i18n.global;
export let sizeType = {
  7: {
    diameter: 180,
    thick: 20,
  },
  13: {
    diameter: 300,
    thick: 20,
  },
};

export let reelType = [
  { label: "未知", value: 0 },
  { label: t("editFormula.whool"), value: 1 },
  { label: t("editFormula.merge"), value: 2 },
  { label: t("editFormula.scattered"), value: 3 },
];

class Reel {
  reelType = 1;
  name = t("editFormula.reel");
  oppositeComponentList = []; //反面放置组件
  frontComponentList = []; //正面放置组件
  reelColor = "rgb(53,95,147)";

  constructor(reelType, name = t("editFormula.reel")) {
    // this.id = getUUID();
    this.reelType = reelType;
    this.name = name;
  }
}

class Package {
  oppositeComponentList = []; //反面放置组件
  frontComponentList = []; //正面放置组件
  constructor(reelType) {
    // this.id = getUUID();
    this.reelType = reelType;
  }
}

class InnerBox {
  reelType = 1;
  leftComponentList = [];
  downComponentList = [];
  rightComponentList = [];
  upComponentList = [];
  frontComponentList = []; //正面放置组件
  backComponentList = [];
  constructor(reelType) {
    // this.id = getUUID();
    this.reelType = reelType;
  }
}

export default defineStore("edit-formula", {
  state: () => {
    return {
      // id: getGUID(),
      selectedComponent: {}, //当前选中的组件
      editCanvas: {
        isDrag: false,
        lockScale: false,
        width: 600,
        height: 600,
        correctX: 300, // 画布中心点,坐标校正
        correctY: 300,
        scale: 120,
      },
      reelConfig: {
        scale: 140,
        deviceCode: "", //设备编号
        recipeNo: 0, //配方编号
        recipeName: "", //配方名称
        customerCode: "", //客户代码
        productModel: "", //产品型号
        packingCode: "", //包装规范
        packingLabelCode: "", //标签规范
        formFactor: "", //封装形式
        baseQuantity: 0, //整盘芯片数量
        reelCode: "", //卷盘料号
        reelDesc: "", //卷盘描述
        reelType: "7",
        reelDiameter: 180,
        reelThickness: 20,
        frontImg: "",
        oppositeImg: "",
        hasReelcombine: true, //是否包含合并盘
        reelColor: "", //卷盘颜色
        traceLabel: false, //追溯标签
        traceLabelSide: 0, //追溯标签位置  0--正面 1--反面
        inOrderEnale: true, //是否排序
        protectiveTapeCode: "", //泡棉料号
        maskingTapeCode: "", //美纹胶
        beltCode: "", //保护带
        scattered: [], //不满盘缠绕方式
        version: "", //版本号
        // grade: "", //等级
        // labelGroup: "", //标签组
        // specialLabel: "", //特殊标签
        // tapewidth: "",
        // boxReelQuantity: "", //每盒盘数
        // boxStandingTime: "", //每盒静置时间
        //adhesiveTapeType: "", //空 -无  1-ESD  2-美纹胶
        //adhesiveTape: "", //胶带料号
        // fromLabel: 1, //追溯标签 1--覆盖 2--撕毁
        // fromLabelSide: 1, //追溯标签位置 1--正面 2--反面
      },
      reelList: [new Reel(1)], //卷盘配置
      packageConfig: {
        scale: 90,
        frontImg: "",
        oppositeImg: "",
        //包装袋配置
        hasBag: true,
        bagCode: "",
        mbbdesc: "",
        bagType: 0, //包装袋类型  0-铝箔袋 1-透明带
        bagWidth: 400,
        bagHeigh: 400,
        mbbImage: "",
        hasLogo: false, //是否包含logo
        hasESD: false, //是否包含ESD
        esdMaterialCode: "", //esd料号
        esdModel: "", //ESD类型
        esdSize: 60,
        esdSizeInBag: 0, //ESD粘贴面
        esdPositionX: 0, //ESD粘贴位置X
        esdPositionY: 0, //ESD粘贴位置Y
        esdPositionR: 0, //ESD粘贴位置R
        mbbUpSide: 0, //包装袋封口时哪个面朝上
        mbBinReelAngle: 0, //入袋角度
        reelInMBBUpSide: 0, //卷盘到袋  0-正面 1-反面
        isNeedSealingVacuum: true, //启用抽真空
        mbbVacuumTime: 0, //抽真空时间
        hasSealing: true, //封口
        ngSealing: false, //ng是否封口
        mbbSealingTime: 0, //封口时间
        mbbSealingTimes: 1, //封口加热次数
        mbbSealingLineDistance: 10, //封口距离
        mbbCoolingTime: 0, //冷却时间
        isNeedSealingNitrogen: false, //注入氮气
        isNeedHeliumTest: false, //是否氦气测试

        //等级标签 不用配置
        hasGradeLabel: 0, //等级标签
        gradeLabelMaterialCode: 0,
        gradeLabelModel: 0,
        gradeLabelSizeInBag: 0,
        gradeLabelPositionX: 0,
        gradeLabelPositionY: 0,
        gradeLabelPositionR: 0,
        gradeLabelDateModel: 0,

        packageList: [new Package(1)],
      },
      innerBox: {
        scale: 100,
        //内盒配置
        boxType: 1, //包装盒类型
        boxMaterialCode: "",
        boxDescription: "",
        boxLength: 400,
        boxWidth: 400,
        boxHeigh: 100,
        bagsPerBox: 1, //每盒盘数
        binsPerBox: 1, //每箱装盒数量
        sealingMaterialCode: "", //封胶料号
        sealingSpec: "", //封胶规格
        sealingMode: "", //封胶方式
        hasQASeals: true, //qa标签
        qaSealsMaterialCode: "", //qa标签料号
        qaSealsType: "", //QA封签类型
        qaSealsLenth: 0,
        qaSealsWidth: 0,
        qaSealsPositionSize: 0, //QA封签位置面
        qaSealsPositionX: 0,
        qaSealsPositionY: 0,
        hasRidingStamps: false, // 有无骑缝章
        ridingStampsMaterialCode: "",
        ridingStampsType: "",
        ridingStampingPosition: "2",
        bubbleBagStamp: false,
        bubbleBagMaterialCode: "", //气泡布
        bubbleBagModel: "", // 气泡袋型号
        bubbleBagWidth: 0,
        bubbleBagLenght: 0,
        hasBoxSprayCodes: false, // 是否内盒上料喷隐形码
        sprayCodesSide: "2", //喷码位置面
        sprayCodesX: 0,
        sprayCodesY: 0,
        sprayCodesR: 0,

        //inSort: 0, //0-无 1-正序 2-倒序
        boxList: [new InnerBox(1)],
      },
      outerBox: {},
      reelImage: [],
      reelIndex: 0, //当前选中的盘
      editType: "reel", //当前编辑类型 reel 卷盘 package 包装袋  innerBox 内盒 outerBox 外盒
      materialList: {
        //所有物料
        reel: [],
        carrierTape: [],
        maskingTape: [],
        foam: [],
        protectiveBelts: [],
        label: [],
        proLabel: [],
        mBBBag: [],
        innerBox: [],
        desiccant: [],
        humidityCard: [],
      },
      labelTemplate: {},
      // auditResults: false, //审核结果
      // creatorId: "", //创建人
    };
  },
  getters: {
    getReelBlockSize(state) {
      return {
        width: state.reelConfig.reelDiameter + 150,
        height: state.reelConfig.reelDiameter + 150,
      };
    },
    getPackageBlockSize(state) {
      return {
        width: state.packageConfig.bagWidth + 150,
        height: state.packageConfig.bagHeigh + 150,
      };
    },
    getAllConfig(state) {
      return state;
    },
    getCurrentReel(state) {
      return state.reelList[state.reelIndex];
    },
    getCurrentPackage(state) {
      return state.packageConfig.packageList[state.reelIndex];
    },
    getCurrentInnerBox(state) {
      return state.innerBox.boxList[state.reelIndex];
    },
    getCurrentFrontReel(state) {
      return state.reelList[state.reelIndex].frontComponentList;
    },
    getCurrenttOppositeReel(state) {
      return state.reelList[state.reelIndex].oppositeComponentList;
    },
  },
  actions: {
    changeEditType(type) {
      this.editType = type;
    },
    changeReelIndex(index) {
      this.reelIndex = index;
    },
    changeReelType(type) {
      this.reelList[this.reelIndex].reelType = type;
      this.packageConfig.packageList[this.reelIndex].reelType = type;
      this.innerBox.boxList[this.reelIndex].reelType = type;
    },
    addReelList() {
      // let index = this.reelList.length + 1;
      // this.reelList.push(new Reel(1, t("editFormula.reel") + index));
      // this.packageConfig.packageList.push(new Package(1));
      // this.innerBox.boxList.push(new InnerBox(1));
    },
    deleteReelList(index) {
      // if (this.reelList.length == 1) {
      //   return ElMessage({
      //     message: "盘数不能少于1",
      //     type: "warning",
      //   });
      // }
      // this.reelList.splice(index, 1);
      // this.innerBox.boxList.splice(index, 1);
      // this.reelIndex--;
    },
    copyReelList(index) {
      // let newReel = JSON.parse(JSON.stringify(this.reelList[index]));
      // let newPackage = JSON.parse(JSON.stringify(this.packageConfig.packageList[index]));
      // let newBox = JSON.parse(JSON.stringify(this.innerBox.boxList[index]));
      // newReel.id = getUUID();
      // newBox.id = getUUID();
      // newReel.name = t("editFormula.reel") + (this.reelList.length + 1);
      // this.reelList.push(newReel);
      // this.packageConfig.packageList.push(newPackage);
      // this.innerBox.boxList.push(newBox);
    },
    changeSelectedComponent(component) {
      this.selectedComponent = component;
    },
    changeDrag(isDrag) {
      this.editCanvas.isDrag = isDrag;
    },
    changeScale(scale) {
      this.editCanvas.scale = scale;
    },
    addComponent(component, type) {
      if (this.editType == "package") {
        let packages = this.packageConfig.packageList[this.reelIndex];
        if (type == "0") {
          packages.frontComponentList.push(component);
        } else {
          packages.oppositeComponentList.push(component);
        }
      } else {
        let reel = this.reelList[this.reelIndex];
        if (type == "0") {
          reel.frontComponentList.push(component);
        } else {
          reel.oppositeComponentList.push(component);
        }
      }
    },
    deleteComponent(component) {
      if (this.editType == "package") {
        if (component.position == "0") {
          let comp =
            this.packageConfig.packageList[this.reelIndex].frontComponentList;
          comp.splice(comp.indexOf(component), 1);
        } else {
          let comp =
            this.packageConfig.packageList[this.reelIndex]
              .oppositeComponentList;
          comp.splice(comp.indexOf(component), 1);
        }
      } else if (this.editType == "reel") {
        let reel = this.reelList[this.reelIndex];
        if (component.position == "0") {
          let comp = reel.frontComponentList;
          comp.splice(comp.indexOf(component), 1);
        } else {
          let comp = reel.oppositeComponentList;
          comp.splice(comp.indexOf(component), 1);
        }
      } else if (this.editType == "innerBox") {
        let box = this.innerBox.boxList[this.reelIndex];
        if (component.position == "7") {
          let comp = box.leftComponentList;
          comp.splice(comp.indexOf(component), 1);
        } else if (component.position == "4") {
          let comp = box.downComponentList;
          comp.splice(comp.indexOf(component), 1);
        } else if (component.position == "6") {
          let comp = box.rightComponentList;
          comp.splice(comp.indexOf(component), 1);
        } else if (component.position == "2") {
          let comp = box.upComponentList;
          comp.splice(comp.indexOf(component), 1);
        } else if (component.position == "5") {
          let comp = box.backComponentList;
          comp.splice(comp.indexOf(component), 1);
        } else if (component.position == "3") {
          let comp = box.frontComponentList;
          comp.splice(comp.indexOf(component), 1);
        }
      }
    },
    moveupComponent(component) {
      if (component.type == "Package") return;
      component.zIndex++;
    },
    movedownComponent(component) {
      if (component.type == "Package") return;
      component.zIndex = component.zIndex <= 1 ? 1 : --component.zIndex;
    },
    exportConfig() {
      downloadTextFile(JSONStringify(this.$state || []), undefined, "json");
    },
    async getAllMaterial() {
      for (let key in this.materialList) {
        this.materialList[key] = [];
      }
      let res = await getMaterial();
      let baseUrl = getEnvConfig.VITE_BASE_URL.replace("api", "");
      res?.items?.forEach((item) => {
        item.imgPath = item.imgPath
          .split(",")
          .filter((i) => !!i)
          .map((i) => baseUrl + i);
        switch (item.materialType) {
          case 0:
            this.materialList.reel.push(item);
            break;
          case 1:
            this.materialList.carrierTape.push(item);
            break;
          case 2:
            this.materialList.maskingTape.push(item);
            break;
          case 3:
            this.materialList.foam.push(item);
            break;
          case 4:
            this.materialList.protectiveBelts.push(item);
            break;
          case 5:
            this.materialList.label.push(item);
            break;
          case 6:
            this.materialList.proLabel.push(item);
            break;
          case 7:
            this.materialList.mBBBag.push(item);
            break;
          case 8:
            this.materialList.innerBox.push(item);
            break;
          case 9:
            this.materialList.desiccant.push(item);
            break;
          case 10:
            this.materialList.humidityCard.push(item);
            break;
          default:
            break;
        }
      });
    },
    async getAllLabelTemplate() {
      this.labelTemplate = {};
      let res = await getlabelsList();
      res?.items.forEach((item) => {
        let labelTemplates = item.labelTemplates.split("|").filter((t) => !!t);
        let labelImgPaths = item.labelImgPaths.split("|").filter((t) => !!t);
        let list = [];
        labelTemplates.forEach((temp, index) => {
          list.push({
            label: temp,
            img:
              getEnvConfig.VITE_BASE_URL.replace("api", "") +
                labelImgPaths?.[index]?.replace(/\\/g, "/") ?? "",
          });
        });
        if (!this.labelTemplate[item.labelSpecCode]) {
          this.labelTemplate[item.labelSpecCode] = [...list];
        } else {
          this.labelTemplate[item.labelSpecCode].push(...list);
        }
      });
    },
    importConfig() {},
    async getRenderImage() {
      let editCanvas = this.editCanvas;
      let reel = this.reelConfig;
      let fel = document.querySelector("#front");
      let oel = document.querySelector("#opposite");
      let flinex = fel.querySelector(".x-line");
      let fliney = fel.querySelector(".y-line");
      let olinex = oel.querySelector(".x-line");
      let oliney = oel.querySelector(".y-line");
      fel.removeChild(flinex);
      fel.removeChild(fliney);
      oel.removeChild(olinex);
      oel.removeChild(oliney);
      let res = await Promise.all([
        canvasCut(fel, false),
        canvasCut(oel, false),
      ]);
      fel.appendChild(flinex);
      fel.appendChild(fliney);
      oel.appendChild(olinex);
      oel.appendChild(oliney);
      let imgs = await Promise.all([
        cutImage(res[0], editCanvas, reel, fel),
        cutImage(res[1], editCanvas, reel, oel),
      ]);
      this.reelImage = imgs;
    },
  },
  persist: {
    storage: sessionStorage,
  },
});

function cutImage(url, can, reel, el) {
  let img = new Image();
  img.src = url;
  let canvas = document.createElement("canvas");
  let canvas2 = document.createElement("canvas");
  return new Promise((resolve) => {
    img.onload = function () {
      canvas.width = el.offsetWidth;
      canvas.height = el.offsetHeight;
      let ctx = canvas.getContext("2d");
      ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
      let imgData = ctx.getImageData(
        can.correctX - reel.reelDiameter / 2,
        can.correctY - reel.reelDiameter / 2,
        reel.reelDiameter,
        reel.reelDiameter
      );
      canvas2.width = reel.reelDiameter;
      canvas2.height = reel.reelDiameter;
      let ctx2 = canvas2.getContext("2d");
      ctx2.putImageData(imgData, 0, 0);
      resolve(canvas2.toDataURL());
    };
  });
}

export let Material = [
  { label: "卷盘", value: "reel", code: 0 },
  { label: "载带", value: "carrierTape", code: 1 },
  { label: "美纹胶", value: "maskingTape", code: 2 },
  { label: "泡棉", value: "foam", code: 3 },
  { label: "保护带", value: "protectiveBelts", code: 4 },
  { label: "产品标签", value: "label", code: 5 },
  { label: "预制标签", value: "proLabel", code: 6 },
  { label: "包装袋", value: "mBBBag", code: 7 },
  { label: "包装盒", value: "innerBox", code: 8 },
  { label: "干燥剂", value: "desiccant", code: 9 },
  { label: "湿度卡", value: "humidityCard", code: 10 },
];
